<!-- 图片上传组件 (暂时是室内图的配置要求) -->
<template>
  <el-upload
    style="display: inline-block;"
    list-type="text"
    :action="uploadImgUrl"
    :show-file-list="false"
    :before-upload="beforeAvatarUpload(row)"
    :on-success="handleSuccess(row)"
    :multiple="true"
    :data="{
      filetype: '房源图片',
      app: 'shulan',
      module: '2',
      sourceKey: '1',
    }"
  >
    <el-button size="small" type="primary">上传图片</el-button>
  </el-upload>
</template>
<script>
import { measureImageInvalid } from "@/utils/utilsNew";
import { mapGetters, mapMutations } from "vuex";
export default {
  name: "ButtonUpdateImg",
  components: {},
  props: {
    row: Object,
  },
  data() {
    this.uploadedImagesList = []; //上传过的图片名称列表

    return {};
  },
  created() {},
  mounted() {
  },
  watch: {},
  computed: {
    ...mapGetters({
      indoorList: "houseInfo/indoorList",
      houDelId: "houseInfo/houDelId",
    }),
  },
  methods: {
    ...mapMutations({
      ADD_IMG: "houseInfo/ADD_IMG",
    }),

    beforeAvatarUpload({ maxlength, minWidth, minHeight }) {
      return (file) => {
        if (this.uploadedImagesList.find((item) => item.name == file.name && item.size == file.size)) {
          this.$message.error("上传的图片重复！");
          return false;
        }
        if (this.indoorList.length >= maxlength) {
          this.handleExceed();
          return false;
        }
        const isJPG = /^image\/(jpeg|png|jpg)$/.test(file.type);
        if (!isJPG) {
          this.$message.error("上传图片只能是 image/jpeg/png 格式!");
          return false;
        }

        let _URL = window.URL || window.webkitURL;
        let src = _URL.createObjectURL(file);
        return measureImageInvalid(src, minWidth, minHeight).catch(() => {
          this.$message.error(`上传图片尺寸不合格`);
          return Promise.reject();
        });
      };
    },
    //上传成功返回
    handleSuccess({ key, maxlength, pixel, tagCode, tagName }) {
      const list = this.indoorList;
      return (res, file) => {
        if (file.response.length <= 0) {
          return this.$message.error("图片上传失败");
        }
        if (list.length < maxlength) {
          this.$message.success("图片上传成功");
          let _item = { name: file.name, size: file.size };
          this.uploadedImagesList.push(_item);

          this.ADD_IMG({
            cover: "0",
            fileId: res[0].id,
            houDelId: this.houDelId,
            type: "pic",
            tagCode,
            tagName: tagName || "未选择",
            url: this.uploadImgUrl + res[0].id,
            ..._item,
          });
        } else {
          this.handleExceed();
        }
      };
    },
    handleExceed() {
      this.$message.error("图片数量已达上限！");
    },
  },
};
</script>
<style></style>
